import {
  getSysParamsTable,
  editSysConfigRecord
} from '../../api/system'
import { forEach } from '@/libs/tools'
import {
  SYS_CONFIG_LIST,
  SYS_CONFIG_DATA_COUNT,
  SYS_CONFIG_HISTORY_DATA,
  SYS_CONFIG_CURRENT_ROW,
  SYS_CONFIG_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    sysConfigList: [],
    sysConfigDataCount: null,
    sysConfigPageSize: 20,
    sysConfigHistoryData: [],
    row: {
      id: '',
      key: '',
      value: '',
      des: ''
    }
  },
  getters: {
    sysConfigList: state => state.sysConfigList
  },
  mutations: {
    [SYS_CONFIG_LIST] (state, data) {
      state.sysConfigList = data
    },
    [SYS_CONFIG_DATA_COUNT] (state, data) {
      state.sysConfigDataCount = data
    },
    [SYS_CONFIG_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [SYS_CONFIG_HISTORY_DATA] (state, data) {
      state.sysConfigHistoryData = data
    },
    [SYS_CONFIG_PAGE_SIZE] (state, data) {
      state.sysConfigPageSize = data
    }
  },
  actions: {
    async getSysConfigList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getSysParamsTable(data)
      let host = resp.data.host
      Object.keys(resp.data.data).forEach((key) => {
        newData = [...newData, {
          title: key,
          value: resp.data.data[key]
        }]
      })
      // resp.data.data.map((item) => {
      //   newData = [...newData, {
      //     host: host,
      //     id: item.id,
      //     des: item.des,
      //     key: item.key,
      //     value: item.value
      //   }]
      // })
      commit(SYS_CONFIG_LIST, newData)
      // commit(SYS_CONFIG_DATA_COUNT, resp.data.data.total)
      // if (newData.length < rootState.sysParamsConfig.sysConfigPageSize) {
      //   commit(SYS_CONFIG_HISTORY_DATA, newData)
      // } else {
      //   commit(SYS_CONFIG_HISTORY_DATA, newData.slice(0, rootState.sysParamsConfig.sysConfigPageSize))
      // }
      return resp
    },
    async editSysConfigData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await editSysConfigRecord(data)
      return resp
    },
    async getSysConfigCurrentRow ({ commit, rootState }, row) {
      commit(SYS_CONFIG_CURRENT_ROW, row)
    },
    async changeSysConfigPage ({ commit, rootState }, index) {
      let data = rootState.sysParamsConfig.sysConfigList
      let _start = (index - 1) * rootState.sysParamsConfig.sysConfigPageSize
      let _end = index * rootState.sysParamsConfig.sysConfigPageSize
      commit(SYS_CONFIG_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeSysConfigPageSize ({ commit, rootState }, value) {
      commit(SYS_CONFIG_PAGE_SIZE, value)
    }
  }
}
